import axios from "axios";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

const service = axios.create({
  // 为了统一管理加上/api前缀，实际发送时通过vite.config.js删除
  baseURL: "/api",
  timeout: 60000,
});

// request拦截器，发送请求时进行拦截
service.interceptors.request.use((config) => {
  // 从浏览器本地存储检测当前操作是否需要token验证
  let user = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user"))
    : {};
  if (user != null) {
    config.headers["token"] = user.token;
  }
  return config;
});

// response拦截器，数据返回时进行拦截
service.interceptors.response.use((res) => {
  return res.data;
});

export default service;
